package Dom4jXML3;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author shkstart
 * @creat 2022-05-21:55
 */
public class ProductXMLParse {
    //扫描器
    public static Scanner scan = new Scanner(System.in);

    public static final String FILE_PATH = "Java_Senior\\d12\\date\\products.xml";

    /**
     * 获取Document对象
     *
     * @return
     * @throws DocumentException
     */
    public static Document getDoc() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(FILE_PATH);
        return doc;
    }

    /**
     * 读取products.xml中的商品信息
     *
     * @return ArrayList
     * @throws DocumentException
     */
    public static ArrayList<Product> showProductInfo() throws DocumentException {

        Document doc = getDoc();
        //获取根元素
        Element root = doc.getRootElement();
        //获取根元素下的所有元素
        List<Element> elementList = root.elements("product");
        //ArrayList集合存储product对象
        ArrayList<Product> productList = new ArrayList<>();
        Product product = null;
        for (Element element : elementList) {
            product = new Product();
            String discount = element.elementTextTrim("discount");
            String manufacturer = element.elementTextTrim("manufacturer");
            String productno = element.elementTextTrim("productno");
            String name = element.elementTextTrim("name");
            String price = element.elementTextTrim("price");
            String unit = element.elementTextTrim("unit");
            String stockcount = element.elementTextTrim("stockcount");
            product.setDiscount(Boolean.parseBoolean(discount));
            product.setManufacturer(manufacturer);
            product.setProductNo(Integer.parseInt(productno));
            product.setName(name);
            product.setPrice(Double.parseDouble(price));
            product.setUnit(unit);
            product.setStockCount(Integer.parseInt(stockcount));
            productList.add(product);

        }
        return productList;
    }

    /**
     * 把对XML文件的操作保存
     */
    public static void saveXML(Document document) {


        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(new FileWriter(FILE_PATH), format);
            writer.write(document);
            //刷新缓冲区
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 根据商品编号修改对应的库存量
     *
     * @param no
     * @param stockcount
     */
    public static void updateXML(int no, int stockcount) {
        boolean isFlag = false;
        try {
            Document doc = getDoc();
            Element root = doc.getRootElement();
            List<Element> elements = root.elements();
            Element element1 = elements.stream().filter(element -> element.elementTextTrim("productno").equals(no + "")).findFirst().orElse(null);
            element1.element("stockcount").setText(stockcount + "");
            isFlag = true;
            saveXML(doc);
            System.out.println("修改成功！！");


        } catch (DocumentException e) {
            e.printStackTrace();
        }
        if (!isFlag) {
            System.out.println("没有找到" + no + "编号的商品");

        }

    }

    /**
     * 根据输入的商品编号，输出对应的商品信息
     *
     * @param no
     */
    public static void searchProduct(int no) {
        try {
            ArrayList<Product> productArrayList = showProductInfo();
            for (Product product : productArrayList) {
                if (product.getProductNo() == no) {
                    System.out.println(product);
                    return;
                }
            }
            System.out.println("没有找到" + no + "编号的商品");
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**-------有点问题-----------测试没结果
     *输入商品编号和购买数量，计算应付金额，如果是折扣商品，打七折；
     * 如果购买数量超过库存量，给出提示库存不足，如果购买成功，扣除相应的数量
     * @param no
     * @param count
     * @return
     */
    public static double buyProduct(int no,int count){
        try {
            Document doc = getDoc();
            Element root = doc.getRootElement();
            List<Element> elements = root.elements();
            double money = 0;
            int newStockCount =0;
            ArrayList<Product> products = showProductInfo();
            for (Product product:products){
                if(product.getProductNo() == no && product.getStockCount() >= count){
                    if(product.isDiscount()){
                        money = product.getPrice()*count*0.7;
                         newStockCount = product.getStockCount()-count;
                        Element element1 = elements.stream().filter(element ->
                                element.elementTextTrim("productno").equals(no + "")).findFirst().orElse(null);
                        if (element1 != null) {
                            element1.element("stockcount").setText(newStockCount+"");
                        }
                        saveXML(doc);
                        return money;
                    }else {
                        money = product.getPrice()*count;
                        newStockCount = product.getStockCount()-count;
                        Element element1 = elements.stream().filter(element ->
                                element.elementTextTrim("productno").equals(no + "")).findFirst().orElse(null);
                        if (element1 != null) {
                            element1.element("stockcount").setText(newStockCount+"");
                        }
                        saveXML(doc);

                        return money;
                    }

                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //没有找到商品System.out.println("没有找到" + no + "编号的商品");
        ////或者是库存量不够
        return 0;
    }

    public static void main(String[] args) {
        ArrayList<Product> list = null;
        try {
            list = showProductInfo();
            //遍历productList数组
            for (Product product1 : list) {
                System.out.println(product1);
            }
            System.out.println("输入商品编号：");
            int no = scan.nextInt();
            System.out.println("根据商品编号" + no + "查找到的商品：");
            searchProduct(no);
            System.out.println();
            System.out.println("输入商品编号和库存数量，修改对应商品的数量");
            System.out.println("商品编号：");
            int no1 = scan.nextInt();
            System.out.println("库存量：");
            int stockCount = scan.nextInt();
            updateXML(no, stockCount);
            System.out.println("————————购买商品————————");
            System.out.println("输入商品编号：");
            int no2 = scan.nextInt();
            System.out.println("输入购买数量：");
            int count = scan.nextInt();
            double money = buyProduct(no2, count);
            if(money > 0){
                System.out.println("您一共消费" + money + "元");
            }else {
                System.out.println("库存不足或没找到商品");
            }
            System.out.println("");
        } catch (DocumentException e) {
            e.printStackTrace();
        }


    }
}
